{% extends "后台管理/template.html" %}

{% block title %}
系统通知(用户通知)
{% endblock %}

{% block css %}
<style>
    .container-fluid {
        max-width: 1200px;
        margin: 0 auto;
        padding: 30px;
    }

    .table-card {
        background: #fff;
        padding: 30px;
        border-radius: 12px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.08);
        border: 1px solid #ebeef5;
    }

    .table-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .search-box {
        display: flex;
        gap: 10px;
        align-items: center;
    }

    .notification-table {
        width: 100%;
        border-collapse: collapse;
    }

    .notification-table th,
    .notification-table td {
        padding: 12px;
        border-bottom: 1px solid #ebeef5;
        text-align: left;
    }

    .notification-table th {
        background: #f8f9fa;
        font-weight: 500;
        color: #333;
    }

    .notification-table tr:hover {
        background: #f8f9fa;
    }

    .notification-content-cell {
        max-width: 300px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        cursor: pointer;
        color: #696cff;
    }

    .notification-content-cell:hover {
        text-decoration: underline;
    }

    .notification-header {
        margin-bottom: 30px;
        padding-bottom: 20px;
        border-bottom: 1px solid #ebeef5;
    }

    .notification-title {
        font-size: 24px;
        font-weight: 600;
        color: #333;
        margin-bottom: 10px;
    }

    .notification-desc {
        color: #666;
        font-size: 14px;
    }

    .form-group {
        margin-bottom: 25px;
    }

    .form-label {
        font-weight: 500;
        margin-bottom: 10px;
        color: #333;
    }

    .form-control {
        border: 2px solid #ebeef5;
        border-radius: 8px;
        padding: 12px 15px;
        transition: all 0.3s ease;
    }

    .form-control:focus {
        border-color: #696cff;
        box-shadow: none;
    }

    .content-textarea {
        min-height: 150px;
        resize: vertical;
    }

    .submit-btn {
        width: 100%;
        height: 48px;
        background: #696cff;
        color: #fff;
        border: none;
        border-radius: 8px;
        font-size: 16px;
        font-weight: 500;
        transition: all 0.3s ease;
    }

    .submit-btn:hover {
        background: #5f62e6;
        transform: translateY(-1px);
    }

    .submit-btn:active {
        transform: translateY(0);
    }

    .submit-btn:disabled {
        background: #b7b9f4;
        cursor: not-allowed;
    }

    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255,255,255,0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    }

    .user-id-input {
        position: relative;
    }

    .user-id-input .form-control {
        padding-right: 100px;
    }

    .verify-btn {
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
        padding: 8px 15px;
        background: #696cff;
        color: #fff;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        transition: all 0.3s ease;
    }

    .verify-btn:hover {
        background: #5f62e6;
    }

    .user-info {
        margin-top: 10px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 8px;
        display: none;
    }

    .user-info.show {
        display: block;
    }

    .user-info-item {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
    }

    .user-info-label {
        width: 80px;
        color: #666;
        font-size: 14px;
    }

    .user-info-value {
        color: #333;
        font-weight: 500;
    }

    .notification-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 20px;
        margin-top: 20px;
    }

    .notification-item {
        background: #fff;
        border-radius: 8px;
        padding: 15px;
        height: 100%;
        display: flex;
        flex-direction: column;
        border: 1px solid #ebeef5;
        transition: all 0.3s ease;
    }

    .notification-item:hover {
        box-shadow: 0 2px 12px rgba(0,0,0,0.08);
    }

    .notification-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        font-size: 14px;
        color: #666;
        padding-bottom: 10px;
        border-bottom: 1px dashed #ebeef5;
    }

    .notification-content {
        color: #333;
        line-height: 1.5;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
    }

    .read-status {
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
    }

    .read-status.unread {
        background: #fff2e8;
        color: #fa8c16;
    }

    .read-status.read {
        background: #f6ffed;
        color: #52c41a;
    }

    .empty-tip {
        text-align: center;
        padding: 40px 0;
        color: #999;
    }

    /* 详情模态框样式 */
    .notification-detail-modal .modal-body {
        padding: 25px;
    }

    .notification-detail-header {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #ebeef5;
    }

    .user-avatar {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        margin-right: 15px;
        object-fit: cover;
    }

    .user-info-detail {
        flex: 1;
    }

    .user-name {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-bottom: 4px;
    }

    .notification-time {
        font-size: 13px;
        color: #666;
    }

    .notification-detail-content {
        font-size: 15px;
        line-height: 1.6;
        color: #333;
        white-space: pre-wrap;
        word-break: break-word;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 加载中遮罩 -->
    <div class="loading-overlay" id="loadingOverlay" style="display: none;">
        <div class="spinner-border text-primary" role="status">
            <span class="sr-only">加载中...</span>
        </div>
    </div>

    <div class="table-card">
        <div class="table-header">
            <h2 class="card-title">系统通知管理</h2>
            <div class="action-buttons">
                <button class="btn btn-primary" onclick="showSendNotificationModal()">
                    <i class='bx bx-plus me-1'></i>发送通知
                </button>
            </div>
        </div>

        <div class="search-box mb-4">
            <input 
                type="text" 
                class="form-control" 
                id="searchUserId" 
                placeholder="输入用户ID查询"
                style="width: 250px;"
            >
            <button 
                class="btn btn-primary" 
                onclick="getNotifications()"
            >
                <i class='bx bx-search me-1'></i>查询
            </button>
        </div>

        <div class="table-responsive">
            <table class="notification-table">
                <thead>
                    <tr>
                        <th style="width: 180px;">发送时间</th>
                        <th style="width: 120px;">状态</th>
                        <th>通知内容</th>
                    </tr>
                </thead>
                <tbody id="notificationList">
                    <!-- 通知列表将通过JS动态插入 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 发送通知模态框 -->
    <div class="modal fade" id="sendNotificationModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">发送系统通知</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="notificationForm">
                        <div class="mb-3">
                            <label class="form-label">用户ID</label>
                            <div class="user-id-input">
                                <input 
                                    type="text" 
                                    class="form-control" 
                                    id="userId" 
                                    placeholder="请输入用户ID"
                                    required
                                >
                                <button type="button" class="verify-btn" onclick="verifyUser()">
                                    验证用户
                                </button>
                            </div>
                            <div class="user-info" id="userInfo">
                                <div class="user-info-item">
                                    <span class="user-info-label">用户名：</span>
                                    <span class="user-info-value" id="username">-</span>
                                </div>
                                <div class="user-info-item">
                                    <span class="user-info-label">账号：</span>
                                    <span class="user-info-value" id="account">-</span>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">通知内容</label>
                            <textarea 
                                class="form-control" 
                                id="content" 
                                rows="4"
                                placeholder="请输入通知内容"
                                required
                            ></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button 
                        type="button" 
                        class="btn btn-primary" 
                        onclick="submitNotification()"
                        id="submitBtn"
                        disabled
                    >
                        发送通知
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 通知详情模态框 -->
    <div class="modal fade" id="notificationDetailModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content notification-detail-modal">
                <div class="modal-header">
                    <h5 class="modal-title">通知详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="notification-detail-header">
                        <img src="" alt="用户头像" class="user-avatar" id="detailUserAvatar">
                        <div class="user-info-detail">
                            <div class="user-name" id="detailUsername"></div>
                            <div class="notification-time" id="detailTime"></div>
                        </div>
                        <span class="badge" id="detailReadStatus"></span>
                    </div>
                    <div class="notification-detail-content" id="detailContent"></div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
let verifiedUserId = null;
let sendNotificationModal = null;
let notificationDetailModal = null;

// 初始化模态框
document.addEventListener('DOMContentLoaded', function() {
    sendNotificationModal = new bootstrap.Modal(document.getElementById('sendNotificationModal'));
    notificationDetailModal = new bootstrap.Modal(document.getElementById('notificationDetailModal'));
});

// 显示发送通知模态框
function showSendNotificationModal() {
    document.getElementById('notificationForm').reset();
    document.getElementById('userInfo').classList.remove('show');
    document.getElementById('submitBtn').disabled = true;
    verifiedUserId = null;
    sendNotificationModal.show();
}

// 验证用户
async function verifyUser() {
    const userId = document.getElementById('userId').value.trim();
    if(!userId) {
        showToast('请输入用户ID', 'warning');
        return;
    }

    try {
        showLoading();
        const response = await fetch('/api/users/get_user_info/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `user_id=${userId}`
        });

        const data = await response.json();
        if(data.code === 200) {
            // 显示用户信息
            const userInfo = document.getElementById('userInfo');
            const username = document.getElementById('username');
            const account = document.getElementById('account');
            
            if(username && account) {
                username.textContent = data.data.username;
                account.textContent = data.data.account;
            }
            
            if(userInfo) {
                userInfo.classList.add('show');
            }
            
            // 启用提交按钮
            const submitBtn = document.getElementById('submitBtn');
            if(submitBtn) {
                submitBtn.disabled = false;
            }
            
            verifiedUserId = userId;
            showToast('用户验证成功', 'success');
        } else {
            throw new Error(data.message || '用户不存在');
        }
    } catch(error) {
        console.error('验证用户失败:', error);
        showToast('验证失败: ' + error.message, 'error');
        
        // 重置状态
        const userInfo = document.getElementById('userInfo');
        const submitBtn = document.getElementById('submitBtn');
        
        if(userInfo) {
            userInfo.classList.remove('show');
        }
        if(submitBtn) {
            submitBtn.disabled = true;
        }
        
        verifiedUserId = null;
    } finally {
        hideLoading();
    }
}

// 提交通知
async function submitNotification() {
    if(!verifiedUserId) {
        showToast('请先验证用户', 'warning');
        return;
    }

    const content = document.getElementById('content').value.trim();
    if(!content) {
        showToast('请输入通知内容', 'warning');
        return;
    }

    try {
        showLoading();
        const response = await fetch('/api/system/add_system_notification/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `user_id=${verifiedUserId}&content=${encodeURIComponent(content)}`
        });

        const data = await response.json();
        if(data.code === 200) {
            showToast('通知发送成功', 'success');
            sendNotificationModal.hide();
            // 刷新通知列表
            getNotifications();
        } else {
            throw new Error(data.message || '发送失败');
        }
    } catch(error) {
        console.error('发送通知失败:', error);
        showToast('发送失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 显示加载中
function showLoading() {
    document.getElementById('loadingOverlay').style.display = 'flex';
}

// 隐藏加载中
function hideLoading() {
    document.getElementById('loadingOverlay').style.display = 'none';
}

// 监听用户ID输入变化
document.getElementById('userId').addEventListener('input', function() {
    // 如果用户ID改变，重置验证状态
    if(this.value.trim() !== verifiedUserId) {
        document.getElementById('userInfo').classList.remove('show');
        document.getElementById('submitBtn').disabled = true;
        verifiedUserId = null;
    }
});

// 获取用户的系统通知
async function getNotifications() {
    const searchUserId = document.getElementById('searchUserId').value.trim();
    if(!searchUserId) {
        showToast('请输入要查询的用户ID', 'warning');
        return;
    }

    try {
        showLoading();
        const response = await fetch(`/api/system/get_system_notification/?user_id=${searchUserId}`);
        const data = await response.json();

        if(data.code === 200) {
            renderNotifications(data.data);
        } else {
            throw new Error(data.message || '获取失败');
        }
    } catch(error) {
        console.error('获取通知失败:', error);
        showToast('获取失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 渲染通知列表
function renderNotifications(notifications) {
    const container = document.getElementById('notificationList');
    
    if(!notifications || notifications.length === 0) {
        container.innerHTML = `
            <tr>
                <td colspan="3" class="text-center py-4">
                    <div class="empty-tip">
                        <i class='bx bx-info-circle fs-3 mb-2'></i>
                        <p>暂无通知记录</p>
                    </div>
                </td>
            </tr>
        `;
        return;
    }
    
    // 按时间排序，最新的在前面
    notifications.sort((a, b) => new Date(b.create_time) - new Date(a.create_time));
    
    container.innerHTML = notifications.map(notification => `
        <tr>
            <td>${formatDateTime(notification.create_time)}</td>
            <td>
                <span class="badge ${notification.is_read ? 'bg-success' : 'bg-warning'}">
                    ${notification.is_read ? '已读' : '未读'}
                </span>
            </td>
            <td class="notification-content-cell" 
                title="点击查看详情" 
                onclick="showNotificationDetail(${notification.id})"
            >
                ${notification.content}
            </td>
        </tr>
    `).join('');
}

// 格式化日期时间
function formatDateTime(dateStr) {
    const date = new Date(dateStr.replace(/-/g, '/'));
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 监听搜索框回车事件
document.getElementById('searchUserId').addEventListener('keyup', function(event) {
    if(event.key === 'Enter') {
        getNotifications();
    }
});

// 显示通知详情
async function showNotificationDetail(notificationId) {
    try {
        showLoading();
        const response = await fetch(`/api/system/get_system_notification_detail/?system_notification_id=${notificationId}`);
        const data = await response.json();

        if(data.code === 200) {
            const detail = data.data;
            
            // 更新模态框内容
            document.getElementById('detailUserAvatar').src = detail.user.avatar || '/static/default-avatar.png';
            document.getElementById('detailUsername').textContent = detail.user.username;
            document.getElementById('detailTime').textContent = formatDateTime(detail.create_time);
            document.getElementById('detailContent').textContent = detail.content;
            
            const statusBadge = document.getElementById('detailReadStatus');
            statusBadge.className = `badge ${detail.is_read ? 'bg-success' : 'bg-warning'}`;
            statusBadge.textContent = detail.is_read ? '已读' : '未读';
            
            // 显示模态框
            notificationDetailModal.show();
        } else {
            throw new Error(data.message || '获取详情失败');
        }
    } catch(error) {
        console.error('获取通知详情失败:', error);
        showToast('获取详情失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}
</script>
{% endblock %}

{% block nav_left %}
{% include '后台管理/components/左侧导航栏.html' %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% block footer %}{% endblock %}